//保存最后的组合结果信息
var SKUResult = {};
var xn_item = {};
var salemsg = "";
//获得对象的key
function getObjKeys(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj)
        if (Object.prototype.hasOwnProperty.call(obj, key))
            keys[keys.length] = key;
    return keys;
}

//把组合的key放入结果集SKUResult
function add2SKUResult(combArrItem, sku) {
	var key = combArrItem.join(";");
    if(SKUResult[key]) {//SKU信息key属性·
        SKUResult[key].count = sku.count;
        SKUResult[key].price=sku.price;
        SKUResult[key].pprice=sku.p_price;
        SKUResult[key].name=sku.name;
        SKUResult[key].skuid=sku.skuid;
        SKUResult[key].isdis=sku.isDiscount;
        SKUResult[key].gift=sku.gift;
        SKUResult[key].isrese=sku.isReseve;
        SKUResult[key].sell=sku.sell;
        SKUResult[key].sellurl=sku.sellurl;
        SKUResult[key].img1=sku.img1;
        SKUResult[key].img2=sku.img2;
        SKUResult[key].img3=sku.img3;
        SKUResult[key].img4=sku.img4;
        SKUResult[key].acvitityicon=sku.acvitityicon;
        SKUResult[key].isHuaBei=sku.isHuaBei;
        SKUResult[key].service=sku.service;
    } else {
        SKUResult[key] = {
            count : sku.count,
            price : sku.price,
            pprice : sku.p_price,
            name : sku.name,
            skuid:sku.skuid,
            isdis:sku.isDiscount,
            gift:sku.gift,
            isrese:sku.isReseve,
            sell:sku.sell,
            sellurl:sku.sellurl,
            img1:sku.img1,
            img2:sku.img2,
            img3:sku.img3,
            img4:sku.img4,
            acvitityicon:sku.acvitityicon,
            isHuaBei:sku.isHuaBei,
            service:sku.service
        };
    }
}

function getStatus(skuid){
	$.get(HOST+"/store/product/getstatus.jhtml?id=" + productId + "&skuId="+skuid, function(result){
	    if(result != null && result != ""){
	    	result = $.parseJSON(result);
	    	var html="";
			if(result.singlebuy == 1){
				salemsg = result.salemsg;
				if(result.statusSell == 1){
					html = "<a href=\"javascript:void(0);\" class=\"buy-button disabled\">商品已下架</a>";
				} else if(result.statusSell == 2){
					html = "<a href=\"javascript:void(0);\" id=\"sale-warn\" parag index=\"detailClickSalewarn\" class=\"buy-button\">开售提醒</a>";
				} else if(result.stock <= 0){
					if(result.isReseve == 1){
						html = "<a href=\"javascript:void(0);\" id=\"buy-reseve\" parag index=\"detailClickBuyreseve\" class=\"buy-button\">立即购买</a>";
					}else{
						if(productId == 15){
							html = "<a href=\"javascript:void(0);\" class=\"buy-button disabled\">已售罄</a>";
						} else{
							html = "<a href=\"javascript:void(0);\" class=\"buy-button disabled\">暂时缺货</a>";
						}
					}
				} else if(result.stock > 0){
					if(result.isReseve == 1){
						html = "<a href=\"javascript:void(0);\" id=\"buy-reseve\" parag index=\"detailClickBuyreseve\" class=\"buy-button\">立即购买</a>";
					}else{
						if(result.typeid == 3 || result.isfast){
							html = "<a href=\"javascript:void(0);\" id=\"buy-goods\" class=\"buy-button\" parag index=\"detailClickBuyNow\">立即购买</a>";
						} else if(result.typeid == 4){
							html = "<a href=\"javascript:void(0);\" id=\"buy-presell\" class=\"buy-button\" parag index=\"detailClickBuyPresell\">预售购买</a>";
						} else{
							html = "<a href=\"javascript:void(0);\" id=\"buy-cart\" class=\"buy-button\" parag index=\"clickAddToCart\">加入购物车</a>";
						}
					}
				}
			} else{
				html = "<a href=\"javascript:void(0);\" class=\"buy-button disabled\">非卖品</a>";
			}
			$(".buy-button").remove();
			$(".product-summary").append(html);
			if(productId == 123){
				if(skuid == 354){
					$("#edgeintro").hide();
					$("#edgelintro").show();
				} else{
					$("#edgelintro").hide();
					$("#edgeintro").show();
				}
			}
	    }
    });
}

//初始化得到结果集
function initSKU() {
	getStatus(preSkuId);
    var i, j, skuKeys = getObjKeys(data);
    for(i = 0; i < skuKeys.length; i++) {
        var skuKey = skuKeys[i];//一条SKU信息key
        var sku = data[skuKey];	//一条SKU信息value
        var skuKeyAttrs = skuKey.split(";"); //SKU信息key属性值数组
		skuKeyAttrs.sort(function(value1, value2) {
			return parseInt(value1) - parseInt(value2);
		});

        //对每个SKU信息key属性值进行拆分组合
		var combArr = combInArray(skuKeyAttrs);
		for(j = 0; j < combArr.length; j++) {
			add2SKUResult(combArr[j], sku);
		}

        //结果集接放入SKUResult
        SKUResult[skuKeyAttrs.join(";")] = {
            count:sku.count,
            price:sku.price,
            pprice:sku.p_price,
            name:sku.name,
            skuid:sku.skuid,
            isdis:sku.isDiscount,
            gift:sku.gift,
            isrese:sku.isReseve,
            sell:sku.sell,
            sellurl:sku.sellurl,
            img1:sku.img1,
            img2:sku.img2,
            img3:sku.img3,
            img4:sku.img4,
            acvitityicon:sku.acvitityicon,
            isHuaBei:sku.isHuaBei,
            service:sku.service
        }
    }
}

/**
 * 从数组中生成指定长度的组合
 * 方法: 先生成[0,1...]形式的数组, 然后根据0,1从原数组取元素，得到组合数组
 */
function combInArray(aData) {
	if(!aData || !aData.length) {
		return [];
	}

	var len = aData.length;
	var aResult = [];

	for(var n = 1; n < len; n++) {
		var aaFlags = getCombFlags(len, n);
		while(aaFlags.length) {
			var aFlag = aaFlags.shift();
			var aComb = [];
			for(var i = 0; i < len; i++) {
				aFlag[i] && aComb.push(aData[i]);
			}
			aResult.push(aComb);
		}
	}
	
	return aResult;
}


/**
 * 得到从 m 元素中取 n 元素的所有组合
 * 结果为[0,1...]形式的数组, 1表示选中，0表示不选
 */
function getCombFlags(m, n) {
	if(!n || n < 1) {
		return [];
	}

	var aResult = [];
	var aFlag = [];
	var bNext = true;
	var i, j, iCnt1;

	for (i = 0; i < m; i++) {
		aFlag[i] = i < n ? 1 : 0;
	}

	aResult.push(aFlag.concat());

	while (bNext) {
		iCnt1 = 0;
		for (i = 0; i < m - 1; i++) {
			if (aFlag[i] == 1 && aFlag[i+1] == 0) {
				for(j = 0; j < i; j++) {
					aFlag[j] = j < iCnt1 ? 1 : 0;
				}
				aFlag[i] = 0;
				aFlag[i+1] = 1;
				var aTmp = aFlag.concat();
				aResult.push(aTmp);
				if(aTmp.slice(-n).join("").indexOf('0') == -1) {
					bNext = false;
				}
				break;
			}
			aFlag[i] == 1 && iCnt1++;
		}
	}
	return aResult;
} 
function putgift(json){
	if($("#gift-list").length>0){
		$("#gift-list").remove();
	}
	if(json!=undefined){
		var html="";
		var giftclass="gift-item";
		var liclass="one-gift";
		if(json.length>1){
			liclass="";
		}
		html+="<li class=\"parameter-item clearfix "+liclass+"\" id=\"gift-list\">";
		html+="<span class=\"parameter-title\">赠品</span>";
		html+="<ul class=\"gifts\">";
		for(var i=0;i<json.length;i++){
			html+="<li class=\""+giftclass+"\"><span class=\"pic\">";
			html+="<img src=\""+json[i].imgUrl+"\"/></span>";
			html+="<a target=\"_blank\" href=\""+HOST+"/store/"+json[i].productid+"_"+json[i].skuid+".html\" class=\"gift-title\">"+json[i].skuname+"</a>";
			html+="<span class=\"gift-num\"></span></li>";
		}
		html+="</ul>";
		html+="</li>";
		if( $("#productService").length > 0){
			$("#productService").before(html);
		} else if($("#huabeifq").length > 0){
			$("#huabeifq").before(html);
		} else{
			$("#numbers").before(html);
		}
	}
}
function putService(json){
	if($("#productService").length>0){
		$("#productService").remove();
	}
	if(json != undefined){
		var html="";
		html+="<li id=\"productService\" class=\"parameter-item clearfix\">";
		html+="<span class=\"parameter-title\">服务</span>";
		html+="<div class=\"insurance-item\">";
		for(var i=0;i<json.length;i++){
			html+="<div class=\"labels clearfix\"><span data-skuid=\""+json[i].id+"\" productid=\""+json[i].productid+"\" class=\"label servie-label\">";
			html+="<img src=\""+json[i].image1+"\" alt=\"\" />"+json[i].name+"</span>";
			html+="<a target=\"_blank\" href=\""+HOST+"/service/safe/\" class=\"detail-link\">详情&nbsp;&gt;&gt;</a>";
			html+="</div>";
		}
		html+="</div>";
		html+="</li>";
		if($("#huabeifq").length > 0){
			$("#huabeifq").before(html);
		} else{
			$("#numbers").before(html);
		}
		$(".servie-label").click(function(){
			var $self = $(this);
			if($self.hasClass('current-label')){
				$self.removeClass("current-label");
			}else{
				$self.addClass("current-label");
			}
		});
	}
}

var flag=true;
//初始化用户选择事件
$(function() {
	if(typeof(webChat) != "undefined"){
		xn_item.item = {id : productId + "_" + $("#skuid").val()};
		webChat.product_detail(xn_item);
	}
	initSKU();
	$('.sku').each(function() {
		var self = $(this);
		var attr_id = self.attr('attr_id');
		if(!SKUResult[attr_id]) {
			self.addClass('display-label');
		}
	}).click(function() {
		var self = $(this);
	    if(self.hasClass('current-label') || self.hasClass('display-label')){
	    	return false;
	    }
		//选中自己，兄弟节点取消选中
		self.toggleClass('current-label').siblings().removeClass('current-label');
		
		//已经选择的节点
		var selectedObjsFlag = $($('.current-label').not(".servie-label").get(0));

		if(selectedObjsFlag.length) {
			//获得组合key价格
			var selectedIdsFlag = [];
			selectedObjsFlag.each(function(index) {
				if(index == 0){
					selectedIdsFlag.push($(this).attr('attr_id'));
				}
			});
			selectedIdsFlag.sort(function(value1, value2) {
				return parseInt(value1) - parseInt(value2);
			});
			var len = selectedIdsFlag.length;
			//用已选中的节点验证待测试节点 underTestObjs
			$(".sku").not(selectedObjsFlag).not(self).each(function() {
				var allLevel = $("#numbers").prev().attr("level");
				var skuSelf = $(this);
				if(allLevel == "3"){
					var siblingsSelectedObj = skuSelf.siblings('.current-label');
					var testAttrIds = [];//从选中节点中去掉选中的兄弟节点
					if(siblingsSelectedObj.length) {
						var siblingsSelectedObjId = siblingsSelectedObj.attr('attr_id');
						for(var i = 0; i < len; i++) {
							(selectedIdsFlag[i] != siblingsSelectedObjId) && testAttrIds.push(selectedIdsFlag[i]);
						}
					} else {
						testAttrIds = selectedIdsFlag.concat();
					}
					var nowNodeNew = parseInt(skuSelf.parent().parent().attr("level"));
					if(nowNodeNew < 2){
						var testAttrIdsnew = testAttrIds.concat(skuSelf.attr('attr_id'));
						testAttrIdsnew.sort(function(value1, value2) {
							return parseInt(value1) - parseInt(value2);
						});
						if(!SKUResult[testAttrIdsnew.join(';')]) {
							var nowNode = skuSelf.parent().parent().attr("level");
							var clickNode = self.parent().parent().attr("level");
							if(nowNode == clickNode){
								skuSelf.addClass('display-label').removeClass('current-label');
							} else{
								var siblingObj = skuSelf.addClass('display-label').removeClass('current-label').siblings().eq(0);
								var showLen = skuSelf.parent().find('.current-label').length;
								if(!siblingObj.hasClass('display-label') && showLen == 0){
									siblingObj.addClass('current-label');
								}
							}
						} else {
							var showLen = skuSelf.parent().find('.current-label').length;
							if(showLen > 0){
								skuSelf.removeClass('display-label');
							} else{
								skuSelf.addClass('current-label').removeClass('display-label');
							}
						}
					} else if(nowNodeNew == 2){
						var oneSpan = $("#product-summary .product-parameter li:eq(1)").find(".labels").find(".current-label");
						var testAttrIdsnew = testAttrIds.concat($(oneSpan).attr('attr_id')).concat(skuSelf.attr('attr_id'));
						testAttrIdsnew.sort(function(value1, value2) {
							return parseInt(value1) - parseInt(value2);
						});
						if(!SKUResult[testAttrIdsnew.join(';')]) {
							var nowNode = skuSelf.parent().parent().attr("level");
							var clickNode = self.parent().parent().attr("level");
							if(nowNode == clickNode){
								skuSelf.addClass('display-label').removeClass('current-label');
							} else{
								var siblingObj = skuSelf.addClass('display-label').removeClass('current-label').siblings().eq(0);
								var showLen = skuSelf.parent().find('.current-label').length;
								if(!siblingObj.hasClass('display-label') && showLen == 0){
									siblingObj.addClass('current-label');
								}
							}
						} else {
							var showLen = skuSelf.parent().find('.current-label').length;
							if(showLen > 0){
								skuSelf.removeClass('display-label');
							} else{
								skuSelf.addClass('current-label').removeClass('display-label');
							}
						}
					} else{
						var oneSpan = $("#product-summary .product-parameter li:eq(1)").find(".labels").find(".current-label");
						var twoSpan = $("#product-summary .product-parameter li:eq(2)").find(".labels").find(".current-label");
						var testAttrIdsnew = testAttrIds.concat($(oneSpan).attr('attr_id')).concat($(twoSpan).attr('attr_id')).concat(skuSelf.attr('attr_id'));
						testAttrIdsnew.sort(function(value1, value2) {
							return parseInt(value1) - parseInt(value2);
						});
						if(!SKUResult[testAttrIdsnew.join(';')]) {
							var nowNode = skuSelf.parent().parent().attr("level");
							var clickNode = self.parent().parent().attr("level");
							if(nowNode == clickNode){
								skuSelf.addClass('display-label').removeClass('current-label');
							} else{
								var siblingObj = skuSelf.addClass('display-label').removeClass('current-label').siblings().eq(0);
								var showLen = skuSelf.parent().find('.current-label').length;
								if(!siblingObj.hasClass('display-label') && showLen == 0){
									siblingObj.addClass('current-label');
								}
							}
						} else {
							var showLen = skuSelf.parent().find('.current-label').length;
							if(showLen > 0){
								skuSelf.removeClass('display-label');
							} else{
								skuSelf.addClass('current-label').removeClass('display-label');
							}
						}
						
					}
				} else{
					var siblingsSelectedObj = skuSelf.siblings('.current-label');
					var testAttrIds = [];//从选中节点中去掉选中的兄弟节点
					if(siblingsSelectedObj.length) {
						var siblingsSelectedObjId = siblingsSelectedObj.attr('attr_id');
						for(var i = 0; i < len; i++) {
							(selectedIdsFlag[i] != siblingsSelectedObjId) && testAttrIds.push(selectedIdsFlag[i]);
						}
					} else {
						testAttrIds = selectedIdsFlag.concat();
					}
					testAttrIds = testAttrIds.concat(skuSelf.attr('attr_id'));
					testAttrIds.sort(function(value1, value2) {
						return parseInt(value1) - parseInt(value2);
					});
					if(!SKUResult[testAttrIds.join(';')]) {
						var nowNode = $(this).parent().parent().attr("level");
						var clickNode = self.parent().parent().attr("level");
						if(nowNode == clickNode){
							skuSelf.addClass('display-label').removeClass('current-label');
						} else{
							var siblingObj = skuSelf.addClass('display-label').removeClass('current-label').siblings().eq(0);
							var showLen = skuSelf.parent().find('.current-label').length;
							if(!siblingObj.hasClass('display-label') && showLen == 0){
								siblingObj.addClass('current-label');
							}
						}
					} else {
						var showLen = skuSelf.parent().find('.current-label').length;
						if(showLen > 0){
							skuSelf.removeClass('display-label');
						} else{
							skuSelf.addClass('current-label').removeClass('display-label');
						}
					}
				}
			});
			var selectedObjs = $('.current-label').not(".servie-label");
			var selectedIds = [];
			selectedObjs.each(function(index) {
				selectedIds.push($(this).attr('attr_id'));
			});
			selectedIds.sort(function(value1, value2) {
				return parseInt(value1) - parseInt(value2);
			});
			
			var price = SKUResult[selectedIds.join(';')].price;
			var pprice=SKUResult[selectedIds.join(';')].pprice;
			var name=SKUResult[selectedIds.join(';')].name;
			var count=SKUResult[selectedIds.join(';')].count;
			var skuid=SKUResult[selectedIds.join(';')].skuid;
			var isdis=SKUResult[selectedIds.join(';')].isdis;
			var gift=SKUResult[selectedIds.join(';')].gift;
			var service=SKUResult[selectedIds.join(';')].service;
			var isrese=SKUResult[selectedIds.join(';')].isrese;
			var sell=SKUResult[selectedIds.join(';')].sell;
			var sellurl=SKUResult[selectedIds.join(';')].sellurl;
			var img1=SKUResult[selectedIds.join(';')].img1;
			var img2=SKUResult[selectedIds.join(';')].img2;
			var img3=SKUResult[selectedIds.join(';')].img3;
			var img4=SKUResult[selectedIds.join(';')].img4;
			var acvitityicon=SKUResult[selectedIds.join(';')].acvitityicon;
			var isHuaBei=SKUResult[selectedIds.join(';')].isHuaBei;
			if(typeof(webChat) != "undefined"){
				xn_item.item = {id : productId + "_" + skuid};
				webChat.product_detail(xn_item);
			}
			if(img1!=null&&img1!=""){
				arrImg = [img1, img2, img3, img4];
				var ltimg1=img1.replace("430_430","64_64");
				var ltimg2=img2.replace("430_430","64_64");
				var ltimg3=img3.replace("430_430","64_64");
				var ltimg4=img4.replace("430_430","64_64");
				var activityiconImag = $("#activityiconImag").attr("src");
				if(acvitityicon != null && acvitityicon != ""){
					if(typeof(activityiconImag) != "undefined"){
						$("#activityiconImag").attr("src",acvitityicon);
					} else{
						var $imageIcon = $('<img class="detail-icon" id="activityiconImag" src="'+acvitityicon+'" width="100" height="100" alt="" />');
						$imageIcon.appendTo(".slider-box");
					}
				} else{
					$("#activityiconImag").remove();
				}
				$("#bx-pager li:eq(0)").addClass('active').siblings().removeClass('active');
				$("#bx-pager li:eq(0) img").attr("src",ltimg1);
				$("#bx-pager li:eq(1) img").attr("src",ltimg2);
				$("#bx-pager li:eq(2) img").attr("src",ltimg3);
				$("#bx-pager li:eq(3) img").attr("src",ltimg4);
				$('.loading').show();
				$(".img-box").find('img').hide();
				$(".img-box").find('img').attr('src',arrImg[$(this).index()]);
				$(this).addClass('active').siblings().removeClass('active');
				$(".img-box").find('img').load(function(){
					$('.loading').hide();
					$(this).show();
				});
				$(".img-box").find('img').attr("src",img1);
			}
			putService(service);
			putgift(gift);
			var priceShowTxt = "敬请期待";
			if(isdis==1){
				$('.product-summary .price').html((pprice == 0.00 ? priceShowTxt : "&yen;"+pprice)+"<i class=\"original-price\">" + (price == 0.00 ? priceShowTxt : "&yen;"+price) +"</i>");
			}else{
				$('.product-summary .price').html((price == 0.00 ? priceShowTxt : "&yen;"+price));
			}
			if(typeof($(".parameter-tip").html()) == "undefined"){
				$(".product-summary .price").after("<p class=\"parameter-tip\"></p>");
			}
			if(sell.length > 0 && sellurl.length > 0){
				$(".parameter-tip").html("<a target=\"_blank\" href=\""+sellurl+"\">"+sell+"</a>");
			} else {
				if(sell.length > 0){
					$(".parameter-tip").html(sell);
				} else{ 
					$(".parameter-tip").remove();
				}
			}
			$(".product-title").html(name);
			$("#skuid").val(skuid);
			if(isHuaBei){
				var huabeifqLen = $("#huabeifq").length;
				if(huabeifqLen == 0){
					var $fghead = $('<li id="huabeifq" class="parameter-item clearfix"></li>');
					var $fgspan = $('<span class="parameter-title">分期</span>');
					var $fgdiv =  $('<div class="huabei-item"><img src="'+IMAGEURL+'/images/huabei-icon.png" width="26" height="26" alt=""/>该商品支持花呗分期</div>');
					$fghead.append($fgspan);
					$fghead.append($fgdiv);
					$("#numbers").before($fghead);
				}
			} else{
				$("#huabeifq").remove();
			}
			getStatus(skuid);
		} else {
			//设置默认价格
			$('.product-summary .price').html('--');
			//设置属性状态
			$('.sku').each(function() {
				SKUResult[$(this).attr('attr_id')] ? $(this).removeClass('display-label') : $(this).addClass('display-label').removeClass('current-label');
			})
		}
	});
	$(".minus").click(function(){
		var count=parseInt($(".number-input").val());
		if(count>1){
			count--;
			$(".number-input").val(count);
		}
	});
	$(".plus").click(function(){
		var count=parseInt($(".number-input").val());
		if(count<parseInt($("#rulecount").val())){
			count++;
			$(".number-input").val(count);
		}else{
			tipsShow("限购"+$("#rulecount").val()+"件，好东西要一起分享哦！");
		}
	});
	$(".number-input").on('input',function(e){  
		   var count=$.trim($(".number-input").val());
		   if(isNaN(count)||count==""){
			   count=1;
		   }else if(parseInt(count)<=0){
			   count=1;
		   }else if(parseInt(count)>parseInt($("#rulecount").val())){
			   count=$("#rulecount").val();
			   tipsShow("限购"+$("#rulecount").val()+"件，好东西要一起分享哦！");
		   }
		   $(".number-input").val(count);
		}); 
	
	/**
	 * 手机添加意外保 by 马甲
	 */
	$(".servie-label").click(function(){
		var $self = $(this);
		if($self.hasClass('current-label')){
			$self.removeClass("current-label");
		}else{
			$self.addClass("current-label");
		}
	});
	
	$(".product-summary").on("click","#buy-cart",function(){
		var pid=$("#pid").val();
		var skuid=$("#skuid").val();
		var count=parseInt($(".number-input").val());
		initdata(pid, skuid, count);
		$("#buy-cart").addClass("disabled");
		Cart.add_number(pid,skuid,count,pids,serviceids,0,addcartcall);
	});
	$(".product-summary").on("click","#buy-goods",function(){
		var pid=$("#pid").val();
		var skuid=$("#skuid").val();
		var count=parseInt($(".number-input").val());
		initdata(pid, skuid, count);
		$("#presell_number").val(count);
		$("#buy-goods").addClass("disabled");
		Cart.buy_now(pids,serviceids);
		flag=true;
	});
	$(".product-summary").on("click","#buy-presell",function(){
		var pid=$("#pid").val();
		var skuid=$("#skuid").val();
		var count=parseInt($(".number-input").val());
		initdata(pid, skuid, count);
		presellShow();
	});
	$(".product-summary").on("click","#sale-warn",function(){
		presellUserShow();
	});
	$(".product-summary").on("click","#buy-reseve",function(){
		window.open(getSaleUrl());
	});
});

function getSaleUrl(){
	if(salemsg != ""){
		return salemsg;
	} else{
		var skuid = $("#skuid").val();
		var z2pro = typeof(skuid) != "undefined" && (parseInt(skuid) >= 52 &&  parseInt(skuid) <= 61);
		if(z2pro){
			return "http://sale.lenovomobile.com/z2pro/";
		} else{
			return "http://sale.lenovomobile.com/z2/";
		}
	}
}

function initdata(pid, skuid, count){
	if($(".current-label").not(".servie-label").length>0){
		var selectedIds = [];
		//已经选择的节点
		var selectedObjs = $('.current-label').not(".servie-label");
		selectedObjs.each(function() {
			selectedIds.push($(this).attr('attr_id'));
		});
		selectedIds.sort(function(value1, value2) {
			return parseInt(value1) - parseInt(value2);
		});
		skuid=SKUResult[selectedIds.join(';')].skuid;
	}
	serviceids = [];
	if($(".servie-label").filter(".current-label").length > 0){
		$(".servie-label").filter(".current-label").each(function() {
			serviceids.push($(this).attr('data-skuid'));
		});
	}
	if(isNaN(pid)||pid==0){
		Message.tipsAB("参数错误");
		return false;
	}
	if(isNaN(skuid)||skuid==0){
		Message.tipsAB("请选择商品");
		return false;
	}
	if(isNaN(count)||count==0){
		Message.tipsAB("请正确选择数量");
		return false;
	}
	if(count>parseInt($("#rulecount").val())){
		Message.tipsAB("该商品限购"+$("#rulecount").val()+"件");
		return false;
	}
	if(!flag) return false;
	flag=false;
}

function addcartcall(message){
	if(message.type=="success"){
		window.location.href=HOST+"/store/cart/";
	}else{
		if(message.context=="PRODUCT_DOWN"){
			Message.tipsAB("抱歉，该商品已下架！");
		}else if(message.context=="NOT_ENOUGH_STOCK"){
			tipsShow("亲，没有那么多库存了");
			var t=setTimeout("$('.product-num tips-txt').fadeOut();",3000);
		}else if(message.context=="PRODUCT_UN_UP"){
			Message.tipsAB("抱歉，该商品暂未开售！");
		}else if(message.context=="NUMBER_IS_SO_MUCH"){
			tipsShow("限购"+message.stock+"件，好东西要一起分享哦！");
			var t=setTimeout("$('.product-num tips-txt').fadeOut();",3000);
		}else if(message.context=="PARAMETERS_ERROR"){
			Message.tipsAB("参数错误！");
		}else{
			Message.tipsAB("异常错误！");
		}
	}
	$("#buy-cart").removeClass("disabled");
	flag=true;
}
function tipsShow(text){
	if($(".product-num .tips-txt").length>0){
		$(".product-num .tips-txt").html(text);
		$(".product-num .tips-txt").show();
	}else{
		var html="<div class=\"tips-txt\">"+text+"</div>";
		$(".product-num").prepend(html);
	}
	var t=setTimeout("$('.product-num .tips-txt').fadeOut();",3000);
}

function presellUserShow(){
	var $remindlayer = $('<div class="pop-layer remind-layer"></div>');
	var $head = $('<div class="pop-layer-head"></div>');
	var $h3 = $('<h3>开售提醒<span class="txt">当商品开卖时，我们会短信通知您</span></h3>');
	var $close = $('<a href="javascript:;" class="close">关闭</a>');
	var $layerbd = $('<div class="pop-layer-bd"></div>');
	var $layerul = $('<ul class="remind-form"></ul>');
	var $layerli1 = $('<li class="clearfix"></li>');
	var $layerliInput = $('<input type="text" id="presellphone" class="txt" placeholder="手机号" />');
	var $layerli2 = $('<li class="yzm clearfix"></li>');
	var $layercode = $('<input type="text" id="presellcode" class="txt" placeholder="验证码" />');
	var $layerspan = $('<span class="yzmImg"></span>');
	var $layerimg = $('<img id="change_security_code_img" src="" width="86" height="38px" alt="" />');
	var $layera = $('<a href="javascript:;" class="link">换一张</a>');
	var $layerli3 = $('<li class="clearfix"></li>');
	var $layerli3Input = $('<input type="button" id="presale_btn" value="提交" class="btn" />');
	var $layerli3Span = $('<span id="presellTip" class="tips"></span>');
	var $overlay = $('<div class="layer-bg" style="display: block;"></div>');
	$head.append($h3);
	$head.append($close);
	$remindlayer.append($head);
	$layerli1.append($layerliInput);
	$layerul.append($layerli1);
	$layerli2.append($layercode);
	$layerspan.append($layerimg);
	$layerli2.append($layerspan);
	$layerli2.append($layera);
	$layerul.append($layerli2);
	$layerli3.append($layerli3Input);
	$layerli3.append($layerli3Span);
	$layerul.append($layerli3);
	$layerbd.append($layerul);
	$remindlayer.append($layerbd);
	$remindlayer.appendTo("body");
	$overlay.appendTo("body");
	$close.click(function() {
		$overlay.remove();
		$remindlayer.remove();
	});
	$("#change_security_code_img").attr("src",HOST+"/store/product/createcode.jhtml?timestamp="+new Date().getTime());
	$layerimg.click(function(){
		$("#change_security_code_img").attr("src",HOST+"/store/product/createcode.jhtml?timestamp="+new Date().getTime());
	});
	$layera.click(function(){
		$("#change_security_code_img").attr("src",HOST+"/store/product/createcode.jhtml?timestamp="+new Date().getTime());
	});
	$layerli3Input.click(function() {
		var pid=$("#pid").val();
		var skuid=$("#skuid").val();
		var phone=$("#presellphone").val();
		var code=$("#presellcode").val();
		var patrn = /^1\d{10}$/;
		if($.trim(phone) == ""){
			$("#presellTip").html("手机号码不能为空！");
		} else if($.trim(code) == ""){
			$("#presellTip").html("验证码不能为空！");
		} else if (!patrn.test(phone)) {
			$("#presellTip").html("手机号码格式错误！");
	    } else{
	    	$.post(HOST+"/store/product/presaleuser.jhtml",
	    			{'presale.productId':pid,'presale.skuId':skuid,'presale.phone':phone,'imagecode':code},
	    			function(data){
	    				if(data != null){
	    					var x = $.parseJSON(data);
	    					if(x.msg == "yes"){
	    						$overlay.remove();
	    						$remindlayer.remove();
	    						Message.tipsPS("提交成功，我们将会在商品开卖时通知您。");
	    					} else if(x.msg == "no"){
	    						$("#change_security_code_img").attr("src",HOST+"/store/product/createcode.jhtml?timestamp="+new Date().getTime());
	    						$("#presellTip").html("手机号或验证码不正确！");
	    					}
	    				}
	    			}
	    	);
	    }
	});
	Avatar.push(['register', document.getElementById("presale_btn"), {parser:clickBtnOrLink, args:["presale_btn_clickAddToCart", "开售提醒预约！"]}]);
}

function presellShow(){
	salemsg = salemsg == "" ? $("#preselltime").val() : salemsg;
	var $detaillayer  = $('<div class="detail-layer sall-rule-layer"></div>');
	var $close  = $('<span class="close"></span>');
	var $presellH3 = $('<h3 class="title">预售商品购买规则说明</h3>');
	var $presellP = $('<p class="fh-time">'+salemsg+'<a target="_blank" href="http://bbs.lenovomobile.cn/huodong/t51390/">了解规则详情>></a></p>');
	var $presellUl = $('<ul class="rules-inner clearfix"></ul>');
	var $presellLi1 = $('<li><strong>无需抢购</strong><span>预售商品，无需参加预约抢购即可购买</span></li>');
	var $presellLi2 = $('<li><strong>按付款顺序发货</strong><span>支付成功后，在预计时间按照付款先后顺序发货</span></li>');
	var $presellLi3 = $('<li><strong>收货信息不可变更</strong><span>为打击黄牛，保护粉丝利益，预售商品收货信息将不可变更</span></li>');
	var $presellLi4 = $('<li><strong>防范黄牛</strong><span>为了保护粉丝利益，打击黄牛，联想手机商城将保留关闭恶意订单的权利</span></li>');
	var $presellA = $('<a class="btn" id="presell_add_cart" href="javascript:;">加入购物车</a>');
	var $overlay = $('<div class="layer-bg" style="display: block;"></div>');
	$detaillayer.append($close);
	$detaillayer.append($presellH3);
	$detaillayer.append($presellP);
	$presellUl.append($presellLi1);
	$presellUl.append($presellLi2);
	$presellUl.append($presellLi3);
	$presellUl.append($presellLi4);
	$detaillayer.append($presellUl);
	$detaillayer.append($presellA);
	$detaillayer.appendTo("body");
	$overlay.appendTo("body");
	
	$close.click(function() {
		$overlay.remove();
		$detaillayer.remove();
		return false;
	});
	$presellA.click(function() {
		var pid=$("#pid").val();
		var skuid=$("#skuid").val();
		var count=parseInt($(".number-input").val());
		Cart.add_number(pid,skuid,count,pids,serviceids,0,addcartcall);
	});
	Avatar.push(['register', document.getElementById("presell_add_cart"), {parser:clickBtnOrLink, args:["presell_clickAddToCart", "预售购买加入购物车"]}]);
}
function uniqueArry(arr) {
    var result = [], hash = {};
    for (var i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem]) {
            result.push(elem);
            hash[elem] = true;
        }
    }
    return result;
}